package com.swordget.conf;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.swordget.commons.Constant;
import com.swordget.dao.impl.TableManagerMysqlDao;
import com.swordget.dao.impl.TableManagerOracleDao;
import com.swordget.dao.impl.TableManagerSqlServerDao;
import com.swordget.util.EnvUitl;
import com.swordget.util.XDataBaseTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileInputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author: David
 * @Date: Created in 14:55 2020/3/26
 * @Description: druid 数据源配置
 * @Modified By:
 * @Version: 0.0.1
 */
@Configuration
public class DruidConfig {

    @Value("${out.setting.switch}")
    private String outSettingSwitch;
    @Value("${out.setting.path}")
    private String outSettingPath;
    @Value("${out.setting.config.name}")
    private String outSettingConfigName;

    public static String tableSpace;

    @Bean
    public DruidDataSource druid() {
        Properties dbProperties = new Properties();
        DruidDataSource dataSource = null;
        try {
            if (Constant.SETTING_ON.equals(outSettingSwitch)) {
                String path = outSettingPath + outSettingConfigName;
                FileInputStream ins = new FileInputStream(path);
                dbProperties.load(ins);
            } else {
                dbProperties.load(DruidConfig.class.getClassLoader().getResourceAsStream(outSettingConfigName));
            }
            EnvUitl.props=dbProperties;
            //设置数据库类型
            setDbType(dbProperties);
            dbProperties = getPropertiesFromSource(dbProperties);
            tableSpace = dbProperties.getProperty("tablespace");
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(dbProperties);
        }catch (Exception e) {
            throw new RuntimeException("load datasource error, dbProperties is :" + dbProperties, e);
        }
        return dataSource;
    }

    private void setDbType(Properties dbProperties) {
        String databaseType=String.valueOf(dbProperties.get(XDataBaseTypeUtil.databaseTypeKey));
        if (databaseType.equals(XDataBaseTypeUtil.Oracle)) {
            XDataBaseTypeUtil.dataBaseType=XDataBaseTypeUtil.Oracle;
        } else if (databaseType.equals(XDataBaseTypeUtil.Mysql)) {
            XDataBaseTypeUtil.dataBaseType=XDataBaseTypeUtil.Mysql;
        } else if (databaseType.equals(XDataBaseTypeUtil.SqlServer)) {
            XDataBaseTypeUtil.dataBaseType=XDataBaseTypeUtil.SqlServer;
        }
    }

    /**
     * 配置Druid的监控
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();
        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        //默认就是允许所有访问
        initParams.put("allow","");
        //访问druid 管理页面黑名单
        //initParams.put("deny","192.168.1.4");
        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 配置一个web监控的filter
     * @return
     */
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());
        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return  bean;
    }

    @Bean
    public StatFilter statFilter() {
        StatFilter statFilter = new StatFilter();
        statFilter.setMergeSql(false);
        return statFilter;
    }

    private Properties getPropertiesFromSource(Properties tempDbProperties) {
        String databaseType = "spring.datasource";
        Properties dbProperties = new Properties();
        for (Object object : tempDbProperties.keySet()) {
            String key = object!=null?object.toString():"";
            if (StringUtils.isNotBlank(databaseType) && key.startsWith(databaseType)) {
                dbProperties.put(key.replaceFirst(databaseType, ""), tempDbProperties.getProperty(key));
            }

            dbProperties.put(key, tempDbProperties.getProperty(key));
        }
        return dbProperties;

    }
}
